package main

import (
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"io"
	"log"
	"os"
	"time"
)

var db *gorm.DB

type User struct {
	ID   int `gorm:"primaryKey"`
	Name string
}
type Article struct {
	gorm.Model
	UserID  int
	Title   string `gorm:"not null;index:search_full,class:FULLTEXT,option:WITH PARSER ngram;check:char_length(title)>0"`
	Content string `gorm:"not null;type:LONGTEXT;index:search_full,class:FULLTEXT,option:WITH PARSER ngram"`
	User    User   `gorm:"foreignKey:UserID;references:ID;constraint:OnUpdate:CASCADE,OnDelete:SET NULL;"`
}

// 设置数据库
func setDatabase() {
	// MySQL配置
	// 手动执行：
	// 登录root
	// CREATE USER 'test'@'localhost' IDENTIFIED BY 'Test@123';
	// GRANT ALL ON *.* TO 'test'@'localhost';
	// mysql -u test -p
	// Test@123
	// CREATE DATABASE test_db;
	const username = "test"
	const password = "Test@123"
	const address = "127.0.0.1:3306"
	const databaseName = "test_db"
	parameter := map[string]string{
		"charset":   "utf8mb4",
		"parseTime": "True",
		"loc":       "Local",
	}
	MySQLDSN := fmt.Sprintf("%s:%s@tcp(%s)/%s?", username, password, address, databaseName)
	for key, value := range parameter {
		MySQLDSN += key + "=" + value + "&"
	}

	mysqlConfig := mysql.Config{
		DSN: MySQLDSN,
	}

	// MySQL输出到屏幕或输出到文件
	var mySQLWritter io.Writer = os.Stdout
	loggerClient := logger.New(
		log.New(mySQLWritter, "\r\n", log.Ldate|log.Ltime|log.Llongfile),
		logger.Config{
			SlowThreshold:             time.Millisecond * 50, // 慢查询标准
			Colorful:                  false,                 // 有颜色
			IgnoreRecordNotFoundError: true,                  // 忽略“记录未找到”错误
			LogLevel:                  logger.Warn,           // 日志等级
		},
	)
	gormConfig := gorm.Config{Logger: loggerClient, PrepareStmt: true}
	var err error
	db, err = gorm.Open(mysql.New(mysqlConfig), &gormConfig)
	if err != nil {
		panic(err)
	}
}

// 迁移数据表
func migrateDataTable() {
	if err := db.AutoMigrate(&User{}); err != nil {
		panic(err)
	}
	if err := db.AutoMigrate(&Article{}); err != nil {
		panic(err)
	}
}

func init() {
	// 设置数据库
	setDatabase()
	// 迁移数据表
	migrateDataTable()
}
